<?php
/**
 * A simple description for this script
 *
 * PHP Version 5.2.0 or Upper version
 *
 * @package    Paylog
 * @author     Hidehito NOZAWA aka Suin <http://suin.asia>
 * @copyright  2010 Hidehito NOZAWA
 * @license    http://www.gnu.org/licenses/gpl-2.0.html GNU GPL v2
 *
 */

class Paylog_Controller_EditBalance extends Paylog_Abstract_Controller
{
	protected $balanceHand = null;
	protected $groupHand   = null;

	protected $balanceId  = null;
	protected $balanceObj = null;

	protected $groups = array();
	protected $input  = array();
	protected $errors = array();

	public function __construct()
	{
		parent::__construct();

		$this->balanceHand = new Paylog_Object_BalanceHandler;
		$this->groupHand   = new Paylog_Object_GroupHandler;
		$this->groupObjs   = $this->groupHand->loads();

		$this->balanceId  = Paylog::get('balance_id');
		$this->balanceObj = $this->balanceHand->load($this->balanceId);

		$this->output['balance_id'] =& $this->balanceId;
		$this->output['input']  =& $this->input;
		$this->output['errors'] =& $this->errors;

		$tags = array();

		foreach ( $this->balanceObj->tagObjs as $tagObj )
		{
			$groupId = $tagObj->getVar('group_id');
			$tags[$groupId] = $tagObj->getVar('id');
		}

		$this->input = array(
			'name'    => $this->balanceObj->getVar('name'),
			'date'    => date('Y-m-d', $this->balanceObj->getVar('date')),
			'price'   => $this->balanceObj->getVar('price'),
			'flow'    => $this->balanceObj->getVar('flow'),
			'book_id' => $this->balanceObj->getVar('book_id'), // TODO
			'tags'    => $tags,
		);

		foreach ( $this->input as $key => $item )
		{
			$this->input[$key] = Paylog::post($key, $item);
		}
	}

	public function main()
	{
		$this->_validateAccess();

		try
		{
			if ( Paylog::post('save') )
			{
				$this->_save();
			}
		}
		catch ( Exception $e )
		{
		}

		$this->_default();
	}

	protected function _validateAccess()
	{
		if ( !Paylog::$cms->isUser() )
		{
			Paylog::redirect("Please login");
		}

		// TODO >> Validate isOwner
	}

	protected function _default()
	{
		$flowOptions = array(
			array(
				'value' => Paylog_Object_Balance::FLOW_OUT,
				'name'  => Paylog::msg("Outgo"),
			),
			array(
				'value' => Paylog_Object_Balance::FLOW_IN,
				'name'  => Paylog::msg("Income"),
			),	
		);

		$this->output['flow_options'] = $flowOptions;

		$groups = array();

		foreach ( $this->groupObjs as $groupObj )
		{
			$tags = array();

			foreach ( $groupObj->tagObjs as $tagObj )
			{
				$tags[] = array(
					'id'   => $tagObj->getVar('id'),
					'name' => $tagObj->getVar('name'),
				);
			}

			$groups[] = array(
				'id'   => $groupObj->getVar('id'),
				'name' => $groupObj->getVar('name'),
				'tags' => $tags,
			);
		}

		$this->output['groups'] = $groups;
		$this->output['token'] = Paylog_Class_Ticket::issue();

		$this->_view();
	}

	protected function _save()
	{
		$this->_validate();

		$this->balanceObj->setVar('date', $this->input['date']);
		$this->balanceObj->setVar('name', $this->input['name']);
		$this->balanceObj->setVar('flow', $this->input['flow']);
		$this->balanceObj->setVar('price', $this->input['price']);
		//$balanceObj->setVar('book_id', $this->input['book_id']);

		if ( !$this->balanceHand->save($this->balanceObj) )
		{
			$this->_addError("Balance updating failed.");
		}

		$relBalanceTagHand = new Paylog_Object_RelBalanceTagHandler;

		if ( !$relBalanceTagHand->deleteByBalanceId($this->balanceId) )
		{
			$this->_addError("Could not unlink balance and tag.");
		}

		foreach ( $this->input['tags'] as $tag )
		{
			$relBalanceTagObj = $relBalanceTagHand->create();
			$relBalanceTagObj->setVar('balance_id', $this->balanceId);
			$relBalanceTagObj->setVar('tag_id', $tag);

			if ( !$relBalanceTagHand->save($relBalanceTagObj) )
			{
				$message = Paylog::msg("Could not tag '{1}' to item", $tag);
				$this->_addError($message);
			}
		}

		$this->_riseError();

		$date = $this->balanceObj->getVar('date');
		$date = date('Y-m-d', $date);
		$params = array(
			'book_id' => $this->balanceObj->getVar('book_id'),
			'start'   => $date,
			'end'     => $date,
		);

		Paylog::redirect("Balance successly updated.", null, 'detail', null, $params);
	}

	protected function _validate()
	{
		$token = Paylog::post('token');

		if ( !Paylog_Class_Ticket::check($token) )
		{
			$this->_addError("Ticket Error");
		}

		if ( !$this->input['name'] )
		{
			$this->_addError("Name is blank.");
		}

		if ( !$this->input['price'] )
		{
			$this->_addError("Price is blank or zero.");
		}
		elseif ( preg_match('/[^0-9]/', $this->input['price']) )
		{
			$this->_addError("Price is not number.");
		}

		if ( !$this->input['date'] )
		{
			$this->_addError("Date is brank.");
		}
		elseif ( !preg_match('/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/', $this->input['date'], $date) )
		{
			$this->_addError("Date format is invalid.");
		}
		elseif ( !checkdate($date[2], $date[3], $date[1]) )
		{
			$this->_addError("Date is invalid.");
		}

		// TODO >> tag options

		$this->_riseError();
	}


	protected function _addError($msg)
	{
		$this->errors[] = Paylog::msg($msg);
	}

	protected function _riseError()
	{
		if ( count($this->errors) > 0 )
		{
			throw new Exception();
		}
	}
}

?>
